<?php

namespace app\goods\controller;

use app\admin\model\Config;
use app\common\controller\Adminbase;
use app\job\SyncGoodsJob;
use app\model\Goods as GoodsModel;
use app\model\GoodsCategory;
use app\model\GoodsSync;
use app\model\GoodsType;
use think\Queue;

class Select extends Adminbase
{
    public function index()
    {
        $model = 'Goods';

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $order = 'sort asc, category_id desc, type desc, id desc';
            foreach ($map as $key => $item) {
                if ($item[0] == 'sort_type') {
                    $value = $item[2];
                    unset($map[$key]);
                    switch ($value) {
                        case 1:
                            $order = 'sale_price asc, sort asc';
                            break;
                        case 2:
                            $order = 'sale_price desc, sort asc';
                            break;
                        case 3:
                            $order = 'commission asc, sort asc';
                            break;
                        case 4:
                            $order = 'commission desc, sort asc';
                            break;
                    }
                }
            }

            $list   = GoodsModel::where($map)->whereIn('plan_type', [1, 2])
                ->withAttr('source', function ($value, $data) {
                    $text = [1 => "<span class='layui-badge layui-bg-blue'>定向</span>", 2 => "<span class='layui-badge layui-bg-orange'>公开</span>"];
                    return $value ? $text[$value] : '';
                })
                ->withAttr('merchant_type', function ($value) {
                    $text = [1 => "<span class='layui-badge layui-bg-blue'>入驻商家</span>", 2 => "<span class='layui-badge layui-bg-orange'>广场商家</span>"];
                    return $value ? $text[$value] : '';
                })
                ->withAttr('is_square', function ($value) {
                    $text = [1 => "<span class='layui-badge layui-bg-green'>是</span>", 0 => "<span class='layui-badge'>否</span>"];
                    return $text[$value];
                })
                ->withAttr('status', function ($value) {
                    $text = [1 => "<span class='layui-badge layui-bg-orange'>已上架</span>", 2 => "<span class='layui-badge'>已下架</span>", 3 => "<span class='layui-badge layui-bg-green'>待选品</span>", 5 => "<span class='layui-badge layui-bg-blue'>已清退</span>"];
                    return $value ? $text[$value] : '';
                })
                ->withAttr('sale_price', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('share_commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('subsidy_commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('plan_type', function ($value) {
                    $text = [1 => '定向计划', 2 => '公开计划', 3 => '机构定向计划', 4 => '机构普通计划'];
                    return $text[$value] ?? '';
                })
                ->field('*')
                ->page($page, $pageSize)
                ->order($order)
                ->with(['category', 'type'])
                ->select();
            $total  = GoodsModel::where($map)->whereIn('plan_type', [1, 2])->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        $category_list = GoodsCategory::field('id, name')
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
        $category      = [];
        foreach ($category_list as $value) {
            if (!key_exists($value['id'], $category))
                $category[$value['id']] = $value['name'];
        }

        $type_list = GoodsType::field('id, name')
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
        $type      = [];
        foreach ($type_list as $value) {
            if (!key_exists($value['id'], $type))
                $type[$value['id']] = $value['name'];
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setAddBtn(false)
            ->setBatchLayerBtn([
                ['title' => '批量设置商品', 'url' => url('batch'), 'class' => 'layui-btn-normal', 'name' => 'form'],
            ])
            ->setConfirmBtn([
                ['title' => '同步定向计划商品', 'url' => url('sync', ['type' => 1]), 'class' => '', 'msg' => '是否同步定向计划商品，同步将在后台执行，请勿重复操作。'],
                ['title' => '同步公开计划商品', 'url' => url('sync', ['type' => 2]), 'class' => 'layui-btn-warm', 'msg' => '是否同步公开计划商品，同步将在后台执行，请勿重复操作。'],
            ])
            ->setDataUrl()
            ->setFormUrl('form')
            ->addSearchItem('title', 'text', '商品标题')
            ->addSearchItem('product_id', 'text', '商品ID')
            ->addSearchItem('shop_appid', 'text', '小店ID')
            ->addSearchItem('category_id', 'select', '商品分类', $category)
            ->addSearchItem('type', 'select', '商品专区', $type)
            ->addSearchItem('plan_type', 'select', '商品计划类型', [1 => '商家定向计划', 2 => '商家公开计划'])
            ->addSearchItem('status', 'select', '状态', [1 => '已上架', 2 => '已下架', 3 => '待选品', 5 => '已清退'])
            ->addSearchItem('sale_price', 'between', '售价', [], 100)
            ->addSearchItem('commission', 'between', '佣金', [], 100)
            ->addSearchItem('sort_type', 'select', '排序', [1 => '按售价升序', 2 => '按售价倒序', 3 => '按佣金升序', 4 => '按佣金倒序'])
            ->setLimit()
            ->setModel($model)
            ->addTableCheckBox('left')
            ->setSwitchTpl('switchTpl', 'status')
            ->setSwitchTpl('amplifyTpl', 'image')
            ->addTableColumn('id', 'ID', null, null, true)
            ->addTableColumn('status', '状态', 168)
            ->addTableColumn('sort', '排序', null, null, false, '', false, '', true)
            ->addTableColumn('product_id', '商品ID', 158)
            ->addTableColumn('shop_appid', '小店ID', 168)
            ->addTableColumn('title', '标题', 550)
            ->addTableColumn('image', '图片', null, '#amplifyTpl')
            ->addTableColumn('category_name', '商品分类', 120)
            ->addTableColumn('type_name', '商品专区', 120)
            ->addTableColumn('stock_num', '库存', 120)
            ->addTableColumn('sale_price', '销售价格', 150)
            ->addTableColumn('commission_rate', '佣金率（%）', 150)
            ->addTableColumn('commission', '佣金', 150)
            ->addTableColumn('share_commission', '分享赚佣金', 150)
            ->addTableColumn('subsidy_commission', '补贴佣金', 150)
            ->addTableColumn('source', '来源', 120)
//            ->addTableColumn('merchant_type', '商家类型', 150)
            ->addTableColumn('plan_type', '商品计划类型', 150)
//            ->addTableColumn('is_square', '是否允许上广场', 130)
            ->addTableOperation()
            ->returnForm();

        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function form()
    {
        $model = 'Goods';

        $id = $this->request->param('id/d');
        if (isset($id) && $id > 0) {
            $info = GoodsModel::get($id);
            $this->assign('id', $id);
            $this->assign('action', 2);
        }

        $categorys = getModelList('GoodsCategory', 'id, name', 'name', ['status' => 1]);
        $types     = getModelList('GoodsType', 'id, name', 'name', ['status' => 1]);
        $builder   = new \app\common\controller\FormBuilder();
        $builder
            ->setModel($model)
            ->setSuccessUrl()
            ->addFormItem('category_id', 'select', '商品分类', '', $categorys)
            ->addFormItem('type', 'select', '商品专区', '', $types)
            ->addFormItem('sort', 'gtnumber', '排序', '值越小排序越靠前')
            ->addFormItem('flags', 'tags', '标识')
            ->setFormData($info)
            ->returnForm();
        $this->assign('module', 'app');
        $this->assign('is_verify', 0);
        return $this->fetch('admin@common/form');
    }

    public function batch()
    {
        $model       = 'Goods';
        $ids         = $this->request->param('ids');
        $info['ids'] = $ids;
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $ids  = explode(',', $data['ids']);
            $save = [];
            if (!empty($data['category_id'])) {
                $save['category_id'] = $data['category_id'];
            }
            if (!empty($data['type'])) {
                $save['type'] = $data['type'];
            }
            if ($save) {
                GoodsModel::where('id', 'in', $ids)->update($save);
                return json(['code' => 0, 'msg' => '操作成功']);
            }
            return json(['code' => 0, 'msg' => '没有任何操作']);
        }

        $category = GoodsCategory::field('id, name')->where('status', 1)->order('sort', 'asc')->order('id', 'asc')->select()->toArray();
        $type     = GoodsType::field('id, name')->where('status', 1)->order('sort', 'asc')->order('id', 'asc')->select()->toArray();
        $this->assign('ids', $ids);
        $this->assign('category', $category);
        $this->assign('type', $type);
        return $this->fetch('goods/batch');
    }

    public function sync()
    {
        $config = Config::where('group', 'wx_team')->column('name, value');
        if (empty($config['wx_team_appid']) || empty($config['wx_team_secret'])) {
            return json(['code' => -1, 'msg' => '请先配置微信带货机构配置信息']);
        }
        $type = $this->request->param('type/d');
        $info = GoodsSync::where('type', $type)->where('status', 0)->order('id desc')->find();
        if ($info) {
            return json(['code' => -1, 'msg' => '后台同步执行中，请勿重复操作！']);
        }
        $res = GoodsSync::create([
            'type' => $type,
        ]);
        if ($res) {
            Queue::push(SyncGoodsJob::class, ['type' => $type], 'tuike');
        }
        return json(['code' => 0, 'msg' => '后台同步执行成功，请勿重复操作！']);
    }

}
